package com.hk.wms.wmsssoserver.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/login")
    public String login(@RequestParam(value="redirec_url",required = false)String redirec_url,
                        @CookieValue(value="sso_user",required = false)String ssoUser,
                        Map map,
                        HttpServletRequest request,
                        HttpServletResponse response){
        if(!StringUtils.isEmpty(ssoUser)){
            //登录过,回到之前的地方，并且把当前ssoserver获取到的cookie以url方式传递给其他域名【cookie同步】
            String url = redirec_url+"?"+"sso_user="+ssoUser;
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "";
        }else {
            //去redis验证，如果没有
            //没有登录过
            map.put("redirec_url",redirec_url);
            return "login";
        }
    }
    @RequestMapping("/dologin")
    public void dologin(String username,String password,String redirec_url,
                            HttpServletRequest request,
                          HttpServletResponse response){
        //1、模拟用户的信息
        Map<String,Object> map = new HashMap<>();
        map.put("username",username);
        map.put("email",username+"@qq.com");
        //2、以上标识用户登录; jwt
        String token = UUID.randomUUID().toString().replace("-", "");
        //redisTemplate.opsForValue().set(token, JSON.toJSONString(map));
        //3、登录成功。做两件事。
        //1）、命令浏览器把当前的token保存为cookie；  sso_user=token
        Cookie cookie = new Cookie("sso_user",token);
        response.addCookie(cookie);
        try {
            response.sendRedirect(redirec_url+"?"+"sso_user="+token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
